package leetcode_1_200;

import java.util.ArrayList;
import java.util.List;

public class LeeCode_103 {
    public static void main(String[] args) {
        System.out.println(zigzagLevelOrder(new TreeNode(3, new TreeNode(9),
                new TreeNode(20, new TreeNode(15), new TreeNode(7)))));

    }

    private static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        List<List<Integer>> ans2 = new ArrayList<>();
        f(ans, root, 0);
        for (int i = 0; i < ans.size(); i++) {
            List<Integer> list = ans.get(i);
            if (i % 2 == 1) {
                List<Integer> newL = new ArrayList<>(list.size());
                for (int j = list.size() - 1; j >= 0; --j) {
                    newL.add(list.get(j));
                }
                ans2.add(newL);
            } else
                ans2.add(list);
        }
        return ans2;
    }
    private static void f(List<List<Integer>> ans, TreeNode node, int depth) {
        if (node == null)
            return;
        if (ans.size() - 1 == depth - 1) {
            List<Integer> list = new ArrayList<>();
            list.add(node.val);
            ans.add(list);
        } else {
            ans.get(depth).add(node.val);
        }
        f(ans, node.left, depth + 1);
        f(ans, node.right, depth + 1);
    }


    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
